<?php
/*
 * @Author: 荷逸
 * @email: 563428234@qq.com
 * @Date: 2020-06-03 15:58:30
 */

namespace app\admin\controller;

use think\facade\Request;
use think\facade\Env;
use think\Validate;
use tools\Compress;

class UpfileController extends Controller
{

    //单位:字节, 等于2MB
    protected $max_size = 3145728;
    //单位:字节, 等于2MB
    protected $max_size_psd = 15728640;
    //保存路径
    protected $save_path = 'uploads/attachment';

    public function upload()
    {
        $file = Request::file('file');
        $suffix    = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        //验证文件
        $this->check([
            'size'   => $file->getSize(),
            'suffix' => $suffix
        ]);
        $info = $file->move($this->save_path);
        if ($info) {
            $imgurl = Env::get('root_path') . 'public' . '/' . $this->save_path . '/' . str_replace("\\", '/', $info->getSaveName());
            // 压缩图片
            $compress = (new Compress($imgurl, 1))->compressImg($imgurl) ;
            $data['url'] = '/' . $this->save_path . '/' .str_replace("\\", '/', $info->getSaveName());
            return $compress ? success('上传成功', '',  $data) : error('上传失败');
        } else {
            return error($file->getError());
        }
    }


    /**
     * 验证
     * @author 吕正辉
     */
    protected function check(array $data)
    {
        //实例化验证器
        $validate = Validate::make([
            'size'   => '<:' . $this->max_size,
            'suffix' => 'in:jpg,png,gif,dcox,psd,doc,PDF,pdf,',
        ]);
        //定义错误提示
        $validate->message([
            'size'   => '文件太大',
            'suffix' => '文件格式不合法',
        ]);
        //验证数据
        if (!$validate->check($data)) {
            return $this->error($validate->getError());
        }
    }
}
